const createError = require('http-errors');
const express = require('express');
const expressJSDocSwagger = require('express-jsdoc-swagger');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const registerRoutes = require('./routes/index');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, '/public/uploads'))); // 上传文件路径
// CORS配置应该放在所有路由之前
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', true); // 允许跨域请求带上cookie
  res.header('Access-Control-Allow-Origin', '*'); // 允许所有域名访问
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // 允许的请求方法
  // 允许客户端使用的所有自定义头部
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, tenant-id, clientid, Accept-Language'); // 允许的请求头
  next();
});
const options = {
  info: {
    version: '1.0.0',
    title: 'API文档',
    license: {
      name: 'MIT',
    },
    description: 'erp_sys API文档',
  },
  security: {
    BearerAuth: {
      type: 'http',
      scheme: 'bearer',
    },
  },
  baseDir: __dirname,
  filesPattern: './**/*.js', // 扫描所有JS文件中的JSDoc注释
  swaggerUIPath: '/api-docs',
  exposeSwaggerUI: true,
  exposeApiDocs: true,
  apiDocsPath: '/v3/api-docs',
  multiple: true,
  swaggerUiOptions: {
  },
};
expressJSDocSwagger(app)(options);
registerRoutes(app); // 注册所有路由

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
